class utils {
    isJson(str) {
        if (typeof str === 'string') {
            try {
                let obj = JSON.parse(str);
                return !!(typeof obj === 'object' && obj);
            } catch (e) {
                return false;
            }
        }
    }

    // 防抖
    debounce(fn, delay) {
        let timer = null
        return function () {
            const context = this
            const args = arguments
            clearTimeout(timer)
            if (delay) {
                timer = setTimeout(() => {
                    fn.apply(context, args)
                }, delay)
            } else {
                fn.apply(context, args)
            }
        }
    }

    getQueryString(url, name) {
        let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
        let urlSearch = ''
        if (typeof url === 'string' && url.indexOf('?') !== -1) {
            urlSearch = url.substr(url.indexOf('?') + 1)
        }
        let r = urlSearch.match(reg)
        if (r != null) {
            return unescape(r[2])
        }
        return null
    }

    getUrlParams(name, params) {
        //console.log(params);
        //构造一个含有目标参数的正则表达式对象
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        //匹配目标参数
        var r = params.match(reg);

        //返回参数值
        if (r != null) {
            return unescape(r[2]);
        }

        return null;
    }
}

let $utils = new utils();
module.exports = $utils;
wx.$util = $utils;
